<?php

namespace App\Http\Controllers\Site\Custom\Purchaser;

use App\B2BProject\Custom\Business\GoodsCategory;
use Auth;
use App\B2BProject\Custom\Purchaser\Enquiry;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\B2BProject\Area;
use App\B2BProject\Site\HelperControllerBuildTrait;

class EnquiryController extends Controller
{
    use HelperControllerBuildTrait;

    /**
     * Display a listing of the resource.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $request->query->set('page', $request->query('page', $request->page));
        $pageSize = $request->query('pageSize', $request->pageSize);

        if ($request->ajax()) {
            switch ($tab = $request->tab) {
                case -1: // 获取两个 TAB 的数据列表
                    $enquires[] = Enquiry::where('member_id', Auth::id())->available()->orderBy('created_at',
                        'desc')->paginate($pageSize);
                    $enquires[] = Enquiry::where('member_id', Auth::id())->unavailable()->orderBy('created_at',
                        'desc')->paginate($pageSize);

                    $data = [];

                    for ($i = 0; $i <= 1; $i++) {
                        foreach ($enquires[$i] as $enquiry) {
                            $data[$i]['detail'][] = [
                                'id'        => $enquiry->id,
                                'goodsname' => $enquiry->title,
                                'price'     => $enquiry->price,
                                'amount'    => $enquiry->amount,
                                'unit'      => $enquiry->unit,
                                'pubdate'   => date('Y-m-d', strtotime($enquiry->created_at)),
                                'district'  => Area::getName($enquiry->province_id) .
                                               ' ' .
                                               Area::getName($enquiry->city_id),
                                'remove'    => $enquiry->status,
                                'supplySrc' => route('account.enquiry.cancel', [$enquiry->id]),
                                'href'      => route('account.enquiry.edit', $enquiry->id),
                            ];
                        }

                        $data[$i]['pagingConfData'] = [
                            'page'     => $enquires[$i]->currentPage(),
                            'pageSize' => $pageSize,
                            'total'    => $enquires[$i]->total(),
                        ];
                    }

                    return response()->json(['data' => $data]);
                    break;
                case 0:
                case 1:
                    $tab      = $tab ^ 1;
                    $enquires = Enquiry::where('member_id', Auth::id())->whereStatus($tab)->orderBy('created_at',
                        'desc')->paginate($pageSize);
                    $data     = [];
                    foreach ($enquires as $enquiry) {
                        $data[] = [
                            'id'          => $enquiry->id,
                            'goodsname'   => $enquiry->title,
                            'price'       => $enquiry->price,
                            'amount'      => $enquiry->amount,
                            'unit'        => $enquiry->unit,
                            'pubdate'     => date('Y-m-d', strtotime($enquiry->created_at)),
                            'district'    => Area::getName($enquiry->province_id) .
                                             ' ' .
                                             Area::getName($enquiry->city_id),
                            'remove'      => $enquiry->status,
                            'supplySrc' => route('account.enquiry.cancel', [$enquiry->id]),
                            'href'        => route('account.enquiry.edit', $enquiry->id),
                        ];
                    }

                    return response()->json([
                        'data' => [
                            'detail'         => $data,
                            'pagingConfData' => [
                                'page'     => $enquires->currentPage(),
                                'pageSize' => $pageSize,
                                'total'    => $enquires->total(),
                            ],
                        ],
                    ]);
                    break;
            }
        }

        return view('host/custom/purchaser/enquiry/index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('host/custom/purchaser/enquiry/create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $member = Auth::user();

        try {
            \DB::transaction(function () use ($request, $member) {
                $validator = Validator::make($request->all(), [
                    'title'                 => 'required',
                    'primary_category_id'   => 'required|numeric',
                    'secondary_category_id' => 'required|numeric',
                    'price'                 => 'required|numeric|min:0',
                    'unit'                  => 'required',
                    'amount'                => 'required|numeric|min:0',
                    'province_id'           => 'required|exists:areas,id,level,1', // 省份 ID
                    'city_id'               => 'required|exists:areas,id,level,2', // 城市 ID
                    'county_id'             => 'required|exists:areas,id,level,3', // 乡镇 ID
                ]);

                $data = $request->only([
                    'title',
                    'price',
                    'unit',
                    'amount',
                    'province_id',
                    'city_id',
                    'county_id',
                ]);

                if ($validator->fails()) {
                    return redirect()->back();
                }
                $enquiry = Enquiry::create($data);

                $primaryCategory
                    = GoodsCategory::GlobalCategory()->whereId($request->primary_category_id)->firstOrFail();
                $primaryCategory->enquiryInPrimary()->save($enquiry);

                $secondaryCategory
                    = $primaryCategory->children()->whereId($request->secondary_category_id)->firstOrFail();
                $secondaryCategory->enquiryInSecondary()->save($enquiry);

                $member->publishes()->save($enquiry);

            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }

        return redirect()->route('account.enquiry.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $enquiries = Enquiry::whereId($id)->firstOrFail();

        return view('host/custom/purchaser/enquiry/edit')->with('enquiries', $enquiries);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $member = Auth::user();

        try {
            \DB::transaction(function () use ($request, $member, $id) {
                $validator = Validator::make($request->all(), [
                    'title'                 => 'required',
                    'primary_category_id'   => 'required|numeric',
                    'secondary_category_id' => 'required|numeric',
                    'price'                 => 'required|numeric|min:0',
                    'unit'                  => 'required',
                    'amount'                => 'required|numeric|min:0',
                    'province_id'           => 'required|exists:areas,id,level,1', // 省份 ID
                    'city_id'               => 'required|exists:areas,id,level,2', // 城市 ID
                    'county_id'             => 'required|exists:areas,id,level,3', // 乡镇 ID
                ]);

                $data = $request->only([
                    'title',
                    'price',
                    'unit',
                    'amount',
                    'province_id',
                    'city_id',
                    'county_id',
                ]);

                if ($validator->fails()) {
                    return redirect()->back();
                }
                $enquiry = Enquiry::AvailableMember()->whereId($id)->firstOrFail();
                $enquiry->update($data);

                $primaryCategory
                    = GoodsCategory::GlobalCategory()->whereId($request->primary_category_id)->firstOrFail();
                $primaryCategory->enquiryInPrimary()->save($enquiry);

                $secondaryCategory
                    = $primaryCategory->children()->whereId($request->secondary_category_id)->firstOrFail();
                $secondaryCategory->enquiryInSecondary()->save($enquiry);

                $member->publishes()->save($enquiry);

            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }

        return redirect()->route('account.enquiry.edit', $id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     *  取消报盘操作
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function cancel(Request $request)
    {
        $id = $request->input('id');

        Enquiry::findOrFail($id)->update(['status' => false]);

        if ($request->ajax()) {
            return $this->index($request);
        }

        return redirect()->back();
    }
}
